package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

/*
 * 核心配置类---替换xml配置文件
 * */
//开启组件扫描
@Configuration//声明当前配置类为核心配置类
@ComponentScan("com.itheima")
@PropertySource(value = "classpath:druid.properties")
@Import(value = {MapperConfig.class})
public class SpringConfig {
    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.pwd}")
    private String pwd;

    //声明一个方法获取数据源对象
    @Bean("dataSource")
    public DataSource getDataSource() {
        //1.创建数据库连接池对象
        DruidDataSource source = new DruidDataSource();
        //2.配置连接数据库的四大基本特征
        source.setDriverClassName(driver);
        source.setUrl(url);
        source.setUsername(username);
        source.setPassword(pwd);
        return source;
    }
    @Bean
    public SqlSessionFactoryBean getSessionBean(/*独立使用@Qualifier("dataSource")*/DataSource dataSource) {//隐藏了byType @Autowired
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.pojo");
        return sqlSessionFactoryBean;
    }

}
